package com.ikun.common.fIlter;


import com.ikun.common.constant.RedisConstant;
import com.ikun.common.manager.RedisManager;
import com.ikun.common.result.Result;
import com.ikun.common.utils.HttpContextUtils;
import com.ikun.common.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * @ClassName BlacklistFilter
 * @Description: 黑名单过滤器 需要实现接口 HandlerInterceptor Ordered
 * @CreateDate: 2024/4/11 16:48
 */
@Component
public class BlacklistFilter implements HandlerInterceptor, Ordered {
    private Logger logger = LoggerFactory.getLogger(BlacklistFilter.class);

    @Autowired
    private RedisManager redisManager;

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 拦截处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("进入黑名单拦截器");
        String ipAddr = HttpContextUtils.getIpAddr(request);
        Set<String> blackSet = redisManager.getSetVal(RedisConstant.BLACK_SET);
        if (blackSet.contains(ipAddr)) {
            logger.info("黑名单校验不通过");
            ResponseUtils.sendResponse(response, new Result<>().fail("你已经进入黑名单中"));
            return false;
        }
        logger.info("黑名单校验通过");
        return true;
    }
}
